import { Injectable } from '@nestjs/common';
import { CreateDictionaryDto } from './dto/create-dictionary.dto';
import { UpdateDictionaryDto } from './dto/update-dictionary.dto';
import { Dictionary } from './entities/dictionary.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';

@Injectable()
export class DictionaryService {
  constructor(
    @InjectRepository(Dictionary)
    private readonly dictionary: Repository<Dictionary>,
  ) {}

  create(createDictionaryDto: CreateDictionaryDto) {
    return 'This action adds a new dictionary';
  }

  findAll() {
    return `This action returns all dictionary`;
  }

  findOne(id: number) {
    return `This action returns a #${id} dictionary`;
  }

  update(id: number, updateDictionaryDto: UpdateDictionaryDto) {
    return `This action updates a #${id} dictionary`;
  }

  remove(id: number) {
    return `This action removes a #${id} dictionary`;
  }

  async findByTypeCode(requestDto: {
    typeCode: string;
    current: number;
    pageSize: number;
    name: string;
  }) {
    const { name, typeCode, current = 1, pageSize = 20 } = requestDto;
    const isPagination = current != null && pageSize != null;
    const result = await this.dictionary.find({
      where: {
        ...(typeCode && { typeCode }),
        ...(name && { label: Like(`%${name}%`) }),
      },
      ...(isPagination && {
        skip: (current - 1) * pageSize,
        take: pageSize,
      }),
    });

    return result;
  }
}
